package com.heima.wemedia.inteceptor;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.threadUtil.ThreadLocalUtil;
import com.heima.utils.common.threadUtil.UserInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class UserInfoInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取请求头信息
        String userId = request.getHeader("userId");
        //判断请求头userId是否为空
        if(StringUtils.isEmpty(userId)){
            //userId为空
            //拦截请求，返回登录认证
            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSON.toJSONString(result));
            return false;

        }
        //获取到userId,将userId设置到ThreadLocal中
        UserInfo userInfo = new UserInfo();
        userInfo.setId(Integer.valueOf(userId));
        ThreadLocalUtil.set(userInfo);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        //调用ThreadLocal的remove方法
        ThreadLocalUtil.remove();
        super.postHandle(request,response,handler,modelAndView);
    }
}
